<template>
    <div>
        <div class="btnContainerBox">
            <template v-for="(btn,index) of localButtons">
                <template v-if="index < buttonCount-1 || index === localButtons.length - 1">
                    <div :class="{'bpm-task-button':true,'bpm-task-button-primary':JSON.parse(btn.style)}" :key="btn.id" @click="btnClick(btn)">
                        <a-icon type="star"  v-if="btn.id === 'btnTracked'" :theme="trackedTheme" :style="{'color':trackedColor}"/>
                        <rx-use-icon v-else-if="btn.icon" v-model="btn.icon"></rx-use-icon>
                        {{getI18Name(btn,'name')}}
                    </div>
                </template>
                <a-dropdown v-else-if="index == buttonCount-1">
                    <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                        {{ $ti18('rxList.moreBtn','更多') }} <a-icon type="down" />
                    </a>
                    <a-menu slot="overlay">
                        <template v-for="(innerBtn,index) of localButtons">
                            <a-menu-item v-if="index >= buttonCount-1 && index < localButtons.length - 1">
                               <div
                                   :key="innerBtn.id"
                                   @click="btnClick(innerBtn)"
                               >
                                   {{getI18Name(innerBtn,'name')}}
                               </div>
                            </a-menu-item>
                        </template>
                    </a-menu>
                </a-dropdown>
            </template>
        </div>
        <a-modal :title="$ti18('rxMsa.actionTips','操作提示')" v-model="showPendStore" @ok="btnPendingOrRestore">
            <p v-if="visiableType=='pending'">{{i18n('msa.pendingTips','您确定要挂起当前任务吗？')}}</p>
            <p v-else-if="visiableType=='restore'">{{i18n('msa.restoreTips','您确定要恢复当前任务吗？')}}</p>
            <p>{{i18n('taskCheck.opinion','意见')}}</p>
            <p>
                <a-textarea v-model="opinion"></a-textarea>
            </p>
        </a-modal>
    </div>
</template>

<script>
import BpmtaskApi from "@/api/bpm/core/bpmTask";
import BpmInstApi from "@/api/bpm/core/bpmInst";
import BpmInstTrackedApi from "@/api/bpm/core/bpmInstTracked";

import {Util,RxUseIcon,App} from "@lowcode/jpaas-common-lib";
import BpmTaskCheck from "./BpmTaskCheck";
import BpmTaskTransferCheck from "./BpmTaskTransferCheck";
import BpmTaskBack from "./BpmTaskBack";
import BpmTaskAddSign from "./BpmTaskAddSign";
import BpmTaskTransferEdit from "./BpmTaskTransferEdit";
import BpmTaskLinkup from "./BpmTaskLinkup";
import BpmTaskCommu from "./BpmTaskCommu";
import BpmTaskRoam from "./BpmTaskRoam";
import TaskCommuReply from "./TaskCommuReply";

import BpmImageView from "../comps/BpmImageView";
import formbase from '@/api/formbase';
import BpmInstStart from "./BpmInstStart";
import BpmTaskRoamTransfer from "./BpmTaskRoamTransfer";
import FlowUtil from "@/views/modules/bpm/js/FlowUtil.js";
import i18nEdit from '../../i18n/i18nEdit.js';
import taskButton from './js/taskButton';
export default {
    name: "task-tool-bar",
    components:{
        RxUseIcon
    },
    props: {
        "bpmTaskDetail":{},
        "taskConfig":{},
        canCommu:{
            default:true
        }
    },
    mixins: [formbase,FlowUtil,i18nEdit,taskButton,App],
    data() {
        return {
            btns: [],
            showDisCardBtn: false,
            isCanBack: false,
            isTransferRoam: false,
            isCanRoamTransfer: false,
            isBatch:false,
            addSignBtn: false,


            backOptions: [],
            canCheck: true,
            allowApprove:{},
            canTransfer: '',
            candicate: -1,
            lockStatus: "",
            //保存状态
            saveStatus: false,
            showPendStore: false,
            visiableType:"",
            opinion: "",

        }
    },
    computed:{
        //按钮数量
        buttonCount(){
            return this.taskConfig.maxButton || 5;
        },

        trackedTheme() {
            return this.bpmTaskDetail.tracked == '1' ? 'filled' : 'outlined';
        },
        trackedColor() {
            return this.bpmTaskDetail.tracked == '1' ? '#eab207' : '#1890ff';
        },
        trackText() {
            return this.bpmTaskDetail.tracked == "1" ? this.i18n('tooBar.btnTracked','已跟踪') : this.i18n('tooBar.btnTrack','跟踪');
        },
        showMoreOptions(){
            let taskShowMore=this.taskConfig.switchOptions.includes("showMoreOptions");
            if(taskShowMore){
                return true;
            }
            let rtn = this.parentVm.processConfig.switchOptions.includes("showMoreOptions");

            return rtn;
        }
    },

    methods: {
        btnClick(btn){
            if(!this.isBuildinBtn(btn.id)){
                this.handMethod(btn)
            }else {
                this[btn['method']](btn)
            }
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"bpmTask",key);
        },
        isBuildinBtn(btn) {
            var btns = ['btnApprove', 'btnSave', 'btnLock', 'btnAddSign',
                'btnReject', 'btnTransfer', 'btnDiscard',
                'btnCommu', 'btnCommuInfo', 'btnReply', 'btnPrint'];
            return btns.indexOf(btn) > -1;
        },
        getCandicate() {
            if (!this.bpmTaskDetail.bpmTask || !this.bpmTaskDetail.bpmTask.hasCandicate) {
                this.candicate = -1;
                this.lockStatus = "";
                return;
            }
            //有侯选人
            if (this.bpmTaskDetail.bpmTask.assignee) {
                this.candicate = 1;
                this.lockStatus = this.i18n('lockStatus.releaseTask','释放任务');
            } else {
                this.candicate = 2;
                this.lockStatus = this.i18n('lockStatus.lockTask','锁定任务');
            }
        },
        doPrint() {
            var baseUrl = process.env.VUE_APP_ADMIN_FRONT;
            var bpmInst = this.bpmTaskDetail.bpmInst;
            var defId = bpmInst.defId;
            var instId = bpmInst.instId;
            var url = baseUrl;

            url += "/flowprint/" + defId;
            if (instId) {
                url += "/" + instId;
            } else {
                url += "/-1";
            }
            let appId=this.curApp.appId;
            url+=`?appId=${appId}`;
            window.open(url);
        },
        startSubProcess(alias) {
            var self_ = this;
            var formType = this.parentVm.processConfig.formType;
            var formData = {};
            if (formType == "online") {
                formData = this.rxForms.getData();
            }else if(formType=="custom"){
                formData=this.customForm.getData();
            }else if(formType=="outsideUrl"){
                formData=this.outSideUrlForm.getData();
            }
            BpmInstApi.getSubProcessFormData({
                defKey: alias, mainDefId: this.parentVm.bpmTask.defId, instId: this.parentVm.instId, formData: formData
            }).then(res => {
                if (!res.success) {
                    return;
                }
                self_.startFlowPage(res.data);
            })
        },
        startFlowPage(data) {
            Util.open({
                component: BpmInstStart,
                curVm: this,
                max: true,
                title: data.defName + this.i18n('startFlow.title','流程启动'),
                data: {
                    defId: data.defId,
                    mainDefId: this.parentVm.bpmTask.defId,
                    mainTaskId: this.parentVm.bpmTask.actTaskId,
                    formData: data.formData,
                    vars: data.vars
                }
            }, function (action) {
            });
        },
        //是否可以审批
        canApprove(){
            if(!this.allowApprove.success){
                this.$message.warn(this.allowApprove.message);

            }
            return this.allowApprove.success;
        },
        approve(){
            if(!this.canApprove()){
                return;
            }
            let quickApprove= this.taskConfig.switchOptions.includes("quickApprove");
            if(quickApprove){
                this.confirmApprove();
            }
            else{
                this.approveTask();
            }
        },
        /**
         * 确认审批。
         */
        confirmApprove(){
            let self_=this;
            this.$confirm({
                title: this.i18n('tooBar.tipInfo','提示信息'),
                content: this.i18n('tooBar.confirmApprove','确认审批吗?'),
                onOk() {
                    self_.quickApprove();
                },
                onCancel() {},
            });
        },
        /**
         * 快速审批。
         * @returns {Promise<void>}
         */
        async quickApprove(){

            let parentVm = this.parentVm;
            if (parentVm.isCanRoamTransfer) {
                this.$message.error(this.i18n('taskCheck.isCanRoam','当前任务正在流转，请取消流转后重试!'));
                return;
            }
            if (parentVm.processConfig.formType == "custom") {
                var res = await this.customForm.valid();
                if (!res) {
                    return;
                }
            }else if (parentVm.processConfig.formType == "outsideUrl") {
                var res = await this.outSideUrlForm.valid();
                if (!res) {
                    return;
                }
            } else {
                let res = await parentVm.$refs.rxForms.valid(true, true);
                if (!res.success) {
                    this.$message.error(res.msg);
                    return;
                }
            }
            let data=this.getApproveData();

            let cmd = {
                taskId: data.taskId,
                checkType: "AGREE",
                opinion: "",
                formJson: data.formJson,
                systemHand: true
            }
            let self_=this;
            BpmtaskApi.checkComplete(cmd).then(resp => {

                if (parentVm.processConfig.formType == 'online') {
                    parentVm.$refs.rxForms.afterSubmit(resp, JSON.parse(data.formJson));
                }
                if(parentVm.isAlone){
                    if (parentVm.destroy) {
                        Util.closeWindow(parentVm, "ok");
                    } else {
                        parentVm.loadTaskInfo();
                    }
                }
                //如果是使用统一URL的方式走下面的代码。
                else{
                    self_.reload();
                }

            })
        },
        getApproveData(){
            let self = this.parentVm;
            var data = {
                taskId: self.taskId,
                nodeExecutors: self.nodeExecutors,
                opinionObj: {},
                systemHand: true,
                taskConfig: this.taskConfig
            }
            var formData = {};
            if (self.processConfig.formType == "custom") {
                formData = this.customForm.getData();
                data.systemHand = false;
            }else if (self.processConfig.formType == "outsideUrl") {
                formData = this.outSideUrlForm.getData();
                data.systemHand = false;
            } else {
                formData = this.rxForms.getData();
                let opinionObj = this.rxForms.getOpinionData();
                data.opinionObj = opinionObj;
            }

            let formJson = JSON.stringify(formData);
            data.formJson = formJson;

            return data;
        },
        async approveTask() {
            let self = this.parentVm;
            if (self.isCanRoamTransfer) {
                this.$message.error(this.i18n('taskCheck.isCanRoam','当前任务正在流转，请取消流转后重试!'));
                return;
            }
            if (self.processConfig.formType == "custom") {
                var res = await this.customForm.valid();
                if (!res) {
                    return;
                }
            }else if (self.processConfig.formType == "outsideUrl") {
                var res = await this.outSideUrlForm.valid();
                if (!res) {
                    return;
                }
            } else {
                let res = await this.rxForms.valid(true, "approve");
                if (!res.success) {
                    this.$message.warn(res.msg);
                    return;
                }
            }
            var data = this.getApproveData();

            //显示更多选项。
            data.showMoreOptions=this.showMoreOptions;
            let self_=this;
            Util.open({
                component: !this.isTransferRoam ? BpmTaskCheck : BpmTaskTransferCheck,
                curVm: self,
                widthHeight: ['860px', '620px'],
                shade:false,
                title: self_.i18n('taskCheck.title','任务审批'),
                data: data
            }, function (action) {
                if (action == 'ok') {
                    //如果是独立打开的那么就关闭窗口。
                    if(self_.isAlone){
                        if (self.destroy) {
                            Util.closeWindow(self, "ok");
                        } else {
                            self.loadTaskInfo();
                        }
                    }
                    //如果是使用统一URL的方式走下面的代码。
                    else{
                        self_.reload();
                    }
                }else if(action == "async"){
                    this.$router.push({ name: 'AccomplishBpm' })
                }
            });
        },
        addSign() {
            let self = this.parentVm;
            Util.open({
                component: BpmTaskAddSign,
                curVm: self,
                widthHeight: ['600px', '380px'],
                title: this.i18n('sign.title','加签'),
                data: {
                    taskId: self.taskId
                }
            }, function (action) {
            });
        },
        getFormJson(){
            let self = this.parentVm;
            var formData = {};
            if (self.processConfig.formType == "custom") {
                formData = this.customForm.getData();
            }else if (self.processConfig.formType == "outsideUrl") {
                formData = this.outSideUrlForm.getData();
            } else {
                formData = this.rxForms.getData();
            }

            let formJson = JSON.stringify(formData);
            return formJson;
        },
        reject() {
            if(!this.canApprove()){
                return;
            }
            let self_=this;
            let self = this.parentVm;
            let formJson =this.getFormJson();
            var opinionObj = {};
            if (self.processConfig.formType != "custom" &&
                self.processConfig.formType != "outsideUrl") {
                opinionObj = this.rxForms.getOpinionData();
            }
            Util.open({
                component: BpmTaskBack,
                curVm: self,
                widthHeight: ['860px', '490px'],
                title: this.i18n('rejectPage.title','任务回退'),
                data: {
                    defId:this.bpmTaskDetail.bpmInst.defId,
                    instId:self.instId,
                    taskId: self.taskId,
                    formJson: formJson,
                    backOptions: this.backOptions,
                    isBatch: this.isBatch,
                    opinionObj: opinionObj
                }
            }, function (action) {
                if (action == 'ok') {
                    if(self.isAlone) {
                        Util.closeWindow(self, "ok");
                    }else{
                        self_.reload();
                    }
                }
            });
        },
        reload() {
            let parentVm = this.parentVm;
            let eventObj = {action: "inst", data: parentVm.instId};
            this.$bus.emit("flowEvent", eventObj);
        },
        doCancelRoamTransfer() {
            let self_ = this
            this.$confirm({
                title: self_.i18n('flowPage.cancelFlowTips','确认取消流转任务吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                zIndex:999999,
                onOk() {
                    BpmtaskApi.cancelTransRoamTask(self_.parentVm.taskId).then(res => {
                        if(self_.isAlone) {
                            Util.closeWindow(self_.parentVm, "ok")
                        }else{
                            self_.reload();
                        }
                    })
                },
            });
        },
        roamInfo() {
            let self = this.parentVm;
            Util.open({
                component: BpmTaskRoam,
                curVm: self,
                widthHeight: ['800px', '450px'],
                title: this.i18n('flowPage.title','任务流转'),
                data: {
                    taskId: self.taskId,
                    subject: self.bpmInst.subject,
                }
            }, function (action) {
                if (action == 'ok') {
                    self.loadTaskInfo();
                }
            });
        },
        doRoamTransfer() {
            if(!this.canApprove()){
                return;
            }
            let self = this.parentVm;
            let this_ = this;
            Util.open({
                component: BpmTaskRoamTransfer,
                curVm: self,
                widthHeight: ['800px', '600px'],
                title: this_.i18n('flowPage.title','任务流转'),
                data: {
                    taskId: self.taskId,
                    subject: self.bpmInst.subject,
                }
            }, function (action) {
                if (action == "ok") {
                    this_.doSaveData(function () {
                        if(self.isAlone) {
                            Util.closeWindow(self, "ok");
                        }else{
                            this_.reload();
                        }
                    });
                }
            });
        },
        doTransfer() {
            if(!this.canApprove()){
                return;
            }
            let self = this.parentVm;
            let self_=this;
            Util.open({
                component: BpmTaskTransferEdit,
                curVm: self,
                widthHeight: ['800px', '450px'],
                title: self_.i18n('transferPage.title','任务转办'),
                data: {
                    taskId: self.taskId,
                    subject: self.bpmInst.subject,
                }
            }, function (action) {
                if (action == "ok") {
                    if(self.isAlone) {
                        Util.closeWindow(self, "ok");
                    }else{
                        self_.reload();
                    }
                }
            });
        },
        doDiscard() {
            if(!this.canApprove()){
                return;
            }
            let self = this;
            let self_ = this.parentVm;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: self.i18n('msa.voidTips','您确定作废当前任务吗？'),
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                zIndex: 20000,
                onOk() {
                    BpmInstApi.cancelProcess(self_.instId, "").then(res => {
                        if(self_.isAlone) {
                            Util.closeWindow(self_, "ok");
                        }else{
                            self.reload();
                        }
                    })
                },
                onCancel() {
                }
            })
        },
        doReplyCommu() {
            let self = this.parentVm;
            var taskId = this.bpmTaskDetail.bpmTask.taskId;
            let self_=this;
            BpmtaskApi.canReplyCommu(taskId).then(res => {
                if (!res.success) {
                    return;
                }
                //回复沟通。
                Util.open({
                    component: TaskCommuReply,
                    curVm: self,
                    widthHeight: ['800px', '450px'],
                    title: self_.i18n('taskComm.replyComm','回复沟通'),
                    data: {
                        taskId: self.taskId
                    }
                }, function (action) {
                    if (action == 'ok') {
                        if(self.isAlone) {
                            Util.closeWindow(self, "ok");
                        }else{
                            self_.reload();
                        }
                    }
                });
            })


        },
        communicate() {
            let self = this.parentVm;
            Util.open({
                component: BpmTaskLinkup,
                curVm: self,
                widthHeight: ['800px', '550px'],
                title: this.i18n('taskComm.taskComm','任务沟通'),
                data: {
                    taskId: self.taskId,
                    subject: self.bpmInst.subject,
                }
            }, function (action) {
                if (action == 'ok') {
                    self.loadTaskInfo();
                }
            });
        },
        doRevoke() {
            let self = this.parentVm;
            //进行任务撤回处理
            BpmtaskApi.revokeCmTask(self.taskId).then(resp => {
                self.loadTaskInfo();
            });
        },

        async doSaveData(callback) {
            var self = this;
            this.saveStatus = true;
            if (self.parentVm.processConfig.formType == "custom") {
                var res = await this.customForm.valid();
                if (!res) {
                    return;
                }
            }else if (self.parentVm.processConfig.formType == "outsideUrl") {
                var res = await this.outSideUrlForm.valid();
                if (!res) {
                    return;
                }
            } else {
                let res = await this.rxForms.valid(false, "save");
                if (!res.success) {
                    this.saveStatus = false;
                    this.$message.warn(res.msg);
                    return;
                }
            }
            let data = {taskId: this.parentVm.taskId, systemHand: true};
            var formData = {};
            if (this.parentVm.processConfig.formType == "custom") {
                formData = this.customForm.getData();
                data.systemHand = false;
            }else if (this.parentVm.processConfig.formType == "outsideUrl") {
                formData = this.outSideUrlForm.getData();
                data.systemHand = false;
            } else {
                formData = this.rxForms.getData();
            }
            var formJson = JSON.stringify(formData);
            data.formJson = formJson;
            BpmtaskApi.saveFormData(data).then(resp => {
                self.saveStatus = false;
                if (self.parentVm.processConfig.formType != "custom" && self.parentVm.processConfig.formType != "outsideUrl") {
                    //表单保存时重新加载表单数据。
                    self.parentVm.loadTaskInfo();
                    self.rxForms.afterSubmit(resp, formData);
                }
                if (callback && typeof callback == 'function') {
                    callback();
                }
            });
        },
        doFlowImg() {
            let self = this.parentVm;
            let formData = {};
            if (self.processConfig.formType == "custom") {
                formData = this.customForm.getData();
            }else if (self.processConfig.formType == "outsideUrl") {
                formData = this.outSideUrlForm.getData();
            } else {
                formData = this.rxForms.getData();
            }
            Util.open({
                component: BpmImageView,
                curVm: self,
                widthHeight: ['1024px', '600px'],
                title: this.i18n('tooBar.btnFlowImg','流程图'),
                data: {
                    taskId: self.taskId,
                    formData: formData,
                    preview: false
                }
            }, function (action) {
            });
        },
        doCommuHistory() {
            this.parentVm.bpmCommuShow = true;
        },
        doMessage() {
            this.parentVm.msgShow = true;
        },
        //更新任务的状态
        doLock() {
            let self = this.parentVm;


            let title = this.candicate == 1 ? this.i18n('msa.releaseTaskTips','释放任务吗?') : this.i18n('msa.lockTaskTips','锁定任务吗?');

            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: title,
                zIndex: 299999,
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    let data = {taskId: self.taskId};
                    BpmtaskApi.updateLocked(data).then(resp => {
                        self.loadTaskInfo();
                    });
                }
            })
        },
        commuInfo() {
            this.$emit("showBpmCommu");
        },
        doTracked() {
            let instId = this.bpmTaskDetail.bpmInst.instId;
            BpmInstTrackedApi.doTracked(instId).then(res => {
                this.bpmTaskDetail.tracked = res.data;
            })
        },
        //挂起或恢复 提示框
        showPendingMode(btn){
            if(!this.canApprove()){
                return;
            }
            let type = 'restore'; //默认 恢复时的参数；
            if(btn && btn.id == 'btnPending'){//挂起
                type = 'pending';
            }
            this.showPendStore=true;
            this.visiableType=type;
        },
        //挂起或恢复
        btnPendingOrRestore(){

            var taskId = this.bpmTaskDetail.bpmTask.taskId;
            let self_=this;
            BpmtaskApi.taskPendingOrRestore(taskId,this.visiableType,this.opinion).then(res=>{
                if(res.success){
                    window.location.reload();
                }
            });
        },
    },
    watch: {
        bpmTaskDetail: {
            handler: function (val, oldval) {
                this.btns = val.taskConfig.buttons;
                this.canCheck = val.canCheck;
                this.canTransfer = val.canTransfer;
                this.isCanBack = val.isCanBack;
                this.showDisCardBtn = val.isShowDiscardBtn;
                this.isTransferRoam = val.isTransferRoam;
                this.isCanRoamTransfer = val.isCanRoamTransfer;
                this.isBatch = val.isBatch;
                this.addSignBtn = val.canAddSign;
                this.allowApprove = val.allowApprove;
                this.backOptions = val.taskConfig.backOptions;
                //
                this.getCandicate();
            },
            deep: true
        },

    },
}
</script>

<style scoped>
.btnContainerBox{
    display: flex;
    align-items: center;
}
.bpm-task-button{
    height: 30px;
    line-height: 30px;
    padding: 0 12px;
    cursor: pointer;
}
.bpm-task-button:hover{
    color: #4285F4;
}
.bpm-task-button.bpm-task-button-primary{
    background-color: #4285F4;
    color: #fff;
    border-radius: 4px;
}
.ant-dropdown-link{
    padding: 0 12px;
}
</style>